package com.tju.eduservice.LeetCode;

import java.util.*;

public class Graph {
    ArrayList<ArrayList<Integer>> graph;
    public Graph(int v){
        graph = new ArrayList<>();
        for (int i = 0; i < v; i++) {
            graph.add(new ArrayList<>());
        }
    }
    public void addEdge(int start,int end){
        graph.get(start).add(end);
    }
    public void removeEdge(int start,int end){
        graph.get(start).remove((Integer) end);
    }
}
class GraphTraversal{
    Graph graph;
    boolean[] visited;
    public GraphTraversal(Graph graph){
        this.graph = graph;
        visited = new boolean[graph.graph.size()];
    }
    //深度优先遍历
    public void DFSTraversal(int v){
        if(visited[v]) return;
        visited[v] = true;
        System.out.println(v + "->");
        ListIterator<Integer> neighbors = graph.graph.get(v).listIterator();
        while (neighbors.hasNext()){
            Integer next = neighbors.next();
            if(! visited[next]){
                DFSTraversal(next);
            }
        }
    }
    public void DFS(){
        for (int i = 0; i < graph.graph.size(); i++) {
            if(! visited[i]){
                DFSTraversal(i);
            }
        }
    }


    //广度优先遍历
    public void BFSTraversal(int v){
        Deque<Integer> queue = new LinkedList<>();
        visited[v] = true;
        queue.addFirst(v);
        while (queue.size() != 0){
            Integer cur = queue.pollFirst();
            System.out.println(cur + "->");
            ListIterator<Integer> neighbors = graph.graph.get(cur).listIterator();
            while (neighbors.hasNext()){
                Integer next = neighbors.next();
                if(! visited[next]){
                    queue.offerLast(next);
                    visited[next] = true;
                }
            }
        }
    }
    public void BFS(){
        for (int i = 0; i < graph.graph.size(); i++) {
            if(! visited[i]){
                BFSTraversal(i);
            }
        }
    }
}












